package com.leetcode;

import com.leetcode.common.TreeNode;
import com.leetcode.util.BinaryTreeUtil;

/**
 * 129. 求根节点到叶节点数字之和
 * 深度优先遍历(从顶自下)
 *
 * @author fy
 * @date 2022/4/24 21:59
 */
public class Solution129 {

    private int res = 0;

    public int sumNumbers(TreeNode root) {
        dfs(root, 0);
        return res;
    }

    private void dfs(TreeNode node, int preVal) {
        if (node == null) {
            return;
        }
        preVal = preVal * 10 + node.val;
        if (node.left == null && node.right == null) {
            res += preVal;
            return;
        }
        dfs(node.left, preVal);
        dfs(node.right, preVal);
    }

    public static void main(String[] args) {
        TreeNode root = BinaryTreeUtil.createTree(new Integer[]{1, 2, 3});
        int res = new Solution129().sumNumbers(root);
        System.out.println(res);
    }

}
